package com.adinnet.api.childStudyRecord.service.impl;

import com.adinnet.api.child.mapper.ChildMapper;
import com.adinnet.api.child.model.Child;
import com.adinnet.api.childMaxStudy.mapper.ChildMaxStudyMapper;
import com.adinnet.api.childMaxStudy.model.ChildMaxStudy;
import com.adinnet.api.childStudyRecord.model.ChildStudyRecord;
import com.adinnet.api.childStudyRecord.mapper.ChildStudyRecordMapper;
import com.adinnet.api.childStudyRecord.model.vo.ChildStudyRecordReq;
import com.adinnet.api.childStudyRecord.model.vo.StudyRecordsListReq;
import com.adinnet.api.childStudyRecord.model.vo.StudyRecordsReq;
import com.adinnet.api.childStudyRecord.service.ChildStudyRecordService;
import com.adinnet.api.childStudyToday.mapper.ChildStudyTodayMapper;
import com.adinnet.api.childStudyToday.model.ChildStudyToday;
import com.adinnet.api.common.VO.ValidableList;
import com.adinnet.api.peaseRecord.mapper.PeaseRecordMapper;
import com.adinnet.api.peaseRecord.model.PeaseRecord;
import com.adinnet.api.peaseRule.mapper.PeaseRuleMapper;
import com.adinnet.api.peaseRule.model.PeaseRule;
import com.adinnet.core.JsonResult;
import com.adinnet.core.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 儿童学习记录表 服务实现类
 * </p>
 *
 * @author zYshuai
 * @since 2020-12-07
 */
@Service
public class ChildStudyRecordServiceImpl extends ServiceImpl<ChildStudyRecordMapper, ChildStudyRecord> implements ChildStudyRecordService {

    @Resource
    private ChildStudyRecordMapper childStudyRecordMapper;

    @Resource
    private ChildStudyTodayMapper childStudyTodayMapper;

    @Resource
    private PeaseRecordMapper peaseRecordMapper;

    @Resource
    private ChildMaxStudyMapper childMaxStudyMapper;

    @Resource
    private ChildMapper childMapper;

    @Resource
    private PeaseRuleMapper peaseRuleMapper;

    /**
     * 学习视频/音频
     */
    @Override
    @Transactional
    public JsonResult videoOrAudio(ChildStudyRecordReq studyRecordReq) {
        //被除数
        Integer divisor = 0;
        Integer pn=0;
        //获取视频获取金豆数的规则
        if (studyRecordReq.getType() == 1) {
            PeaseRule videoPeaseRule = peaseRuleMapper.selectOne(new QueryWrapper<PeaseRule>().eq("deleted", 0).eq("code", "study_video_3").last("limit 1"));
            pn=videoPeaseRule.getPeaseNum();
            if (null != videoPeaseRule) {
                List<String> videoNums = getNum(videoPeaseRule.getMessage());
                if (CollectionUtils.isNotEmpty(videoNums)) {
                    divisor = Integer.parseInt(videoNums.get(0));
                }
            }
        }
        //获取音频获取金豆数的规则
        if (studyRecordReq.getType() == 2) {
            PeaseRule voicePeaseRule = peaseRuleMapper.selectOne(new QueryWrapper<PeaseRule>().eq("deleted", 0).eq("code", "study_voice_3").last("limit 1"));
            pn=voicePeaseRule.getPeaseNum();
            if (null != voicePeaseRule) {
                List<String> voiceNums = getNum(voicePeaseRule.getMessage());
                if (CollectionUtils.isNotEmpty(voiceNums)) {
                    divisor = Integer.parseInt(voiceNums.get(0));
                }
            }
        }
        //获取金豆数
        Integer peaseNum = 0;
        if (divisor != 0) {
            peaseNum = new BigDecimal(studyRecordReq.getStudyTime())
                    .divide(new BigDecimal(divisor).multiply(new BigDecimal(60)), 5, BigDecimal.ROUND_UP).setScale(0, BigDecimal.ROUND_UP).intValue();
        }
        peaseNum=peaseNum*pn;
        studyRecordReq.setPeaseNum(peaseNum);
        ChildStudyRecord studyRecord = new ChildStudyRecord();
        BeanUtils.copyProperties(studyRecordReq, studyRecord);
        Date createdDate = new Date();
        studyRecord.setCreatedDate(createdDate);

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String formatdate = df.format(createdDate);
        childStudyRecordMapper.insert(studyRecord);
        setOrUpdateStudyToday(studyRecordReq, formatdate);
        savePeaseRecord(studyRecordReq, studyRecord.getId());
        //判断当天是否分享过【share_study_qq，share_study_wechat，share_study_wechat_friends，share_study_dingding】
        List<PeaseRecord> isSHare = getIsSHare(studyRecordReq.getChildId());
        if (CollectionUtils.isEmpty(isSHare)) {
            //修改儿童待分享豆豆数
            updateChidldSharePeaseNum(peaseNum, studyRecordReq.getChildId());
        }
        return JsonResult.ok().put("data", peaseNum);
    }

    //判断当天是否分享过
    public List<PeaseRecord> getIsSHare(Integer childId) {
        return peaseRecordMapper.getIsSHare(childId);
    }

    //修改儿童待分享豆豆数
    private void updateChidldSharePeaseNum(Integer peaseNum, Integer childId) {
        Child child1 = childMapper.selectById(childId);
        if (null == child1) {
            throw new BizException("儿童信息错误!");
        }
        Child child = new Child();
        child.setSharePeaseNum(child1.getSharePeaseNum() + peaseNum);
        childMapper.update(child, new QueryWrapper<Child>().eq("id", childId));
    }

    //获取字符串中的数字
    public List<String> getNum(String message) {
        List<String> digitList = new ArrayList<String>();
        Pattern p = Pattern.compile("[^0-9]");
        Matcher m = p.matcher(message);
        String result = m.replaceAll("");
        for (int i = 0; i < result.length(); i++) {
            digitList.add(result.substring(i, i + 1));
        }
        return digitList;
    }

    /**
     * 批量上传学习词汇或短句记录接口
     *
     * 1，计算此次提交学习的总时长
     *
     * 2，查询t_child_study_today是否有今日学习记录，没有的话插入今日的学习记录，有的话累加今日的学习时长
     *
     * 3，查根据词汇/短句id查出t_child_max_study表里的每条的记录最大的数据，修改或更新
     *
     * 4，插入t_child_study_record每条词汇/短句的学习记录
     *
     * 5，插入t_pease_record每次词汇/短句的金豆记录
     *
     * 6，返回本次学习累计金豆数
     *
     * 7, 2021-01-14 业务逻辑调整，app只能传总学习时长，无法传每次学习的学习时长
     *
     * 8，2021-01-14 单词和短句的学习逻辑修改，可以只传学习时长，不传学习记录集合
     *
     * 9, 2021-01-14 app通过学习获得的金豆数可以累计并延缓分享，所以此处要修改儿童表新增的字段待分享豆豆数
     *
     * 10，2021-01-19 跟产品确认，通过学习单词短语的过程获得的学习金豆，每次学习不管学习了几条单词和词汇都只生成一条金豆记录
     * @param reqs
     */
    @Override
    @Transactional
    public Integer uploadWordOrSentenceStudyRecords(StudyRecordsListReq reqs) {
        Child c = new Child();
        Integer sum=0;
        Integer childId = reqs.getChildId();
        Integer type = reqs.getType();
        //获取总的学习时长(2021-01-14 业务逻辑调整，app只能传总学习时长，无法传每次学习的学习时长)
        //这种情况只需要记录一条学习记录，更新每日学习时长，
        Integer studyTime = reqs.getStudyTime();
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //判断是否有今日学习记录，更新或新增今日学习记录
        ChildStudyRecordReq childStudyRecordReq = new ChildStudyRecordReq();
        childStudyRecordReq.setChildId(childId);
        childStudyRecordReq.setType(type);
        childStudyRecordReq.setStudyTime(studyTime);
        setOrUpdateStudyToday(childStudyRecordReq,date);
        //如果不传学习记录，即代表用户只停留在单词和词汇的学习页面，没有跟读，此时只记录学习时长
        if(reqs.getStudyRecords()==null||reqs.getStudyRecords().isEmpty()){
            ChildStudyRecord studyRecord1 = new ChildStudyRecord();
            studyRecord1.setChildId(childId);
            studyRecord1.setStudyTime(studyTime);
            studyRecord1.setType(type);
            childStudyRecordMapper.insert(studyRecord1);
        }else{
            List<StudyRecordsReq> list = reqs.getStudyRecords();
            Child child = childMapper.selectById(childId);
            //获取总金豆数
            sum = list.stream().mapToInt(StudyRecordsReq::getPeaseNum).sum();
            //获取累计开口学习次数
            Integer studyNum = list.stream().mapToInt(StudyRecordsReq::getStudyNum).sum();
            //插入或更新最高学习记录
            //插入学习记录
            for (StudyRecordsReq req : list) {
                ChildMaxStudy mStudy = new ChildMaxStudy();
                ChildStudyRecord studyRecord = new ChildStudyRecord();
                BeanUtils.copyProperties(req,mStudy);
                mStudy.setType(type);
                mStudy.setChildId(childId);
                setOrUpdateMaxStudy(mStudy);
                BeanUtils.copyProperties(req,studyRecord);
                studyRecord.setChildId(childId);
                studyRecord.setType(type);
                //无法记录每条记录的学习时长，所以定义为总学习时长。
                studyRecord.setStudyTime(studyTime);
                childStudyRecordMapper.insert(studyRecord);

            }
            //插入金豆学习记录
            if(sum>0){
                PeaseRecord peaseRecord = new PeaseRecord();
                peaseRecord.setType(1);
                peaseRecord.setChildId(childId);
                peaseRecord.setPeaseNum(sum);
                if(type==3){
                    peaseRecord.setSource(5);
                    peaseRecord.setSourceName("重点词汇");
                }else{
                    peaseRecord.setSource(6);
                    peaseRecord.setSourceName("跟读训练");
                }
                //2021-01-19 跟产品确认，通过学习单词短语的过程获得的学习金豆，每次学习不管学习了几条单词和词汇都只生成一条金豆记录
                //所以此处不会具体到哪一条的学习金豆
                peaseRecord.setStatus(0);
                peaseRecordMapper.insert(peaseRecord);
            }
            //更新累计学习次数
            c.setId(childId);
            c.setSumStudyNum(child.getSumStudyNum()==null?studyNum:child.getSumStudyNum()+studyNum);
            List<PeaseRecord> isSHare = peaseRecordMapper.getIsSHare(childId);
            //更新待分享金豆数,判断当天是否分享过学习金豆，分享过的话就不能再分享了
            if(CollectionUtils.isEmpty(isSHare)){
                c.setSharePeaseNum(child.getSharePeaseNum()+sum);
            }
            childMapper.updateById(c);
        }
        return sum;
    }


    /**
     * 保存豌豆记录表
     *
     * @param studyRecordReq
     */
    public void savePeaseRecord(ChildStudyRecordReq studyRecordReq,Integer studyRecordId) {
        PeaseRecord peaseRecord = new PeaseRecord();
        if (1 == studyRecordReq.getType()) {
            peaseRecord.setSource(3);
            peaseRecord.setSourceName("视频学习");
        } else if (2 == studyRecordReq.getType()) {
            peaseRecord.setSource(4);
            peaseRecord.setSourceName("音频学习");
        }
        peaseRecord.setType(1);
        peaseRecord.setChildStudyRecordId(studyRecordId);
        peaseRecord.setChildId(studyRecordReq.getChildId());
        peaseRecord.setPeaseNum(null == studyRecordReq.getPeaseNum() ? 0 : studyRecordReq.getPeaseNum());
        peaseRecord.setStatus(0);
        peaseRecordMapper.insert(peaseRecord);
    }

    /**
     * 添加每天学习时间记录或累计时长
     */

    public void setOrUpdateStudyToday(ChildStudyRecordReq studyRecordReq, String date) {
            QueryWrapper<ChildStudyToday> wrapper = new QueryWrapper<>();
            wrapper.eq("child_id", studyRecordReq.getChildId()).eq("study_date", date).last("limit 1");
            ChildStudyToday studyToday = childStudyTodayMapper.selectOne(wrapper);
            if (null == studyToday) {
                //新增记录
                ChildStudyToday childStudyToday = new ChildStudyToday();
                childStudyToday.setChildId(studyRecordReq.getChildId());
                childStudyToday.setType(studyRecordReq.getType());
                childStudyToday.setStudyDate(new Date());
                childStudyToday.setStudyTime(studyRecordReq.getStudyTime());
                if (1 == studyRecordReq.getType()) {
                    childStudyToday.setStudyVideoTime(studyRecordReq.getStudyTime());
                }
                childStudyTodayMapper.insert(childStudyToday);
            } else {
                //修改记录-累计时长
                ChildStudyToday childStudyToday = new ChildStudyToday();
                childStudyToday.setStudyTime(studyToday.getStudyTime() + studyRecordReq.getStudyTime());
                if (1 == studyRecordReq.getType()) {
                    childStudyToday.setStudyVideoTime(studyToday.getStudyVideoTime() + studyRecordReq.getStudyTime());
                }
                childStudyTodayMapper.update(childStudyToday, wrapper);
            }
        }


    /**
     * 添加或更新词汇或短语最高得分记录
     */

    public void setOrUpdateMaxStudy(ChildMaxStudy childMaxStudy) {
        QueryWrapper<ChildMaxStudy> wrapper = new QueryWrapper<>();
        wrapper.eq("child_id", childMaxStudy.getChildId()).eq("type", childMaxStudy.getType())
                .eq("third_id",childMaxStudy.getThirdId()).eq("deleted",0).last("limit 1");
        ChildMaxStudy maxStudy = childMaxStudyMapper.selectOne(wrapper);
        if (null == maxStudy) {
            //新增记录
            childMaxStudyMapper.insert(childMaxStudy);
        } else if(childMaxStudy.getPeaseNum()>maxStudy.getPeaseNum()){
            //修改记录
            maxStudy.setPeaseNum(childMaxStudy.getPeaseNum());
            maxStudy.setReadUrl(childMaxStudy.getReadUrl());
            maxStudy.setResult(childMaxStudy.getResult());
            childMaxStudyMapper.updateById(maxStudy);
        }
    }
}
